import random
def pin(type):
  "this function generates a random pin # valid to the type (total number of pin code possibilities)"
  a = 0
  b = type - 1
  return random.randint(a,b)

def key(code, type):
    "this function takes a master key code, and generates 1 random valid key for that code"
    type = int(type)
    codelen = len(str(code))
    code = list(str(code))
    code = [int(number) for number in code]
    subcode = []
    count = int()
    for number in code :
        newnum = (number + pin(type - 2) + 2) % type
        if newnum == number - 1 :
            newnum = number
        if count >= 1 :
            num1 = subcode[-1]
            num2 = subcode[len(subcode) - 2]
            if num1 == num2 :
                pretest = num1
            else : 
                pretest = 1000
            while abs(prenum - newnum) > 5 or newnum == pretest :
                newnum = (number + pin(type - 2) + 2) % type
                        
        subcode.append(newnum)
        count += 1
        prenum = newnum
    subcodestring = [str(n) for n in subcode]
    subcodestring = [''.join(subcodestring)]
    return subcodestring

def keyset(master, type, subs) :
  "this function takes a master code and calls key() subs times to generate a set of sub keys"
  count = int()
  subkeys = []
  while count != subs :
    newkey = key(master, type)
    while subkeys.count(newkey) >= 1 :
      newkey = key(master, type)
    subkeys.append(newkey)
    count += 1
  return subkeys

def keygroups(master, groups, keys, type) :
  "this function takes a master keycode, and n groups of n keys and generates a sub master key for each group, and a subs"
  groupmasters = keyset(master, type, groups)
  groups2 = []
  for group in groupmasters :
    for gmaster in group :
      gmaster = str(gmaster)
      groups2.append(gmaster)
      newgroup = keyset(gmaster, type, keys)
        
      groups2.append(newgroup)

  return groups2

print keygroups("00000", 100, 10, 10)
